package siruna.WE.core;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.Map.Entry;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import siruna.WE.DeviceDependent.DeviceDependentListener;
import siruna.WE.DeviceDependent.WidgetEngine1;
import siruna.WE.core.model.VisualBlock;

public class Engine {
	private Subject subject;
	private HashMap<Integer, ZipFile> zip;

	HashMap<Integer, Widget> widgets;
	private String deviceDependentFunctionBlocks;

	public void register(DeviceDependentListener dl) {
		subject.setDeviceDependentListener(dl);

	}

	public Engine() {
		super();
		subject = new Subject();
		widgets = new HashMap<Integer, Widget>();

	}

	public void setZipFiles(HashMap<Integer, ZipFile> zip) {
		this.zip = zip;
	}

	public HashMap<Integer, InputStream> requestIcons() {
		HashMap<Integer, InputStream> a = new HashMap<Integer, InputStream>();

		Set<Entry<Integer, ZipFile>> set = zip.entrySet();

		Iterator<Entry<Integer, ZipFile>> it = set.iterator();

		while (it.hasNext()) {
			Entry<Integer, ZipFile> entry = it.next();

			ZipEntry e = entry.getValue().getEntry("icon.jpg");

			try {
				InputStream is = entry.getValue().getInputStream(e);
				a.put(entry.getKey(), is);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return a;
	}

	public void requestWidget(int id) {
		XMLParser parser = new XMLParser(subject, id);
		parser.setDeviceFunctBlockLocation(deviceDependentFunctionBlocks);
		System.out.println("id in de widgets:" + id);

		ZipFile z = zip.get(id);
		System.out.println("z:" + z);

		Widget w = parser.parseWidgetFile(zip.get(id));
		
		
		
		widgets.put(id, w);
		subject.updateWidget(id);

	}

	public LinkedHashMap<String, VisualBlock> getVisualBlocks(int widgetId) {
		System.out.println("id af de widgets:" + widgetId);
		System.out.println("hierzo: " + widgets.get(widgetId));
		return widgets.get(widgetId).getVisblocks();
	}
	
	public Widget getWidget(int widgetId) {
		System.out.println("id af de widgets:" + widgetId);
		System.out.println("hierzo: " + widgets.get(widgetId));
		return widgets.get(widgetId);
	}
	
	
	
	
	public void setListener(DeviceDependentListener dd) {
		// TODO Auto-generated method stub
		subject.setDeviceDependentListener(dd);

	}

	public void setDeviceFunctBlockLocation(String deviceDependentFunctionBlocks) {
		this.deviceDependentFunctionBlocks = deviceDependentFunctionBlocks;
		
	}

}
